using System.Collections.Generic;
using System.Linq;
using DataAssociations.AssociationMiningAlgorithms.FpTree;
using DataAssociations.AssociationMiningAlgorithms.Helpers;

namespace DataAssociations.AssociationMiningAlgorithms.Facades
{
    public class FpGrowthAlgorithmRunner : IAssociationFinder
    {
        public void FindAssociations(List<List<string>> inputSets, string path, int minSupport, int minConfidence,
            bool overWriteFile)
        {
            var knownElements = inputSets.SelectMany(x => x.Select(y => y)).Distinct();
            var occurances = knownElements.ToDictionary(knownElement => knownElement, knownElement => 0);
            foreach (var set in inputSets)
            {
                foreach (var element in set)
                {
                    occurances[element]++;
                }
            }
            var sortedOccurances =
                (from entry in occurances
                 orderby entry.Value
                     descending
                 select entry.Key).ToList();

            for (var i = 0; i < inputSets.Count; i++)
            {
                inputSets[i] = inputSets[i].OrderBy(x => x, new CustomComparer(occurances)).ToList();
            }
            var fpgTree = new FPGTree(inputSets);
            var hashedPaths = fpgTree.BuildHashedPathsToEachLeaf();
            var conditionalPatternsBuilder = new ConditionalBaseBuilder(fpgTree, sortedOccurances, minConfidence);
            var generatedFrequentPatterns = conditionalPatternsBuilder.Generate(hashedPaths);
            var fileWriter = new FileWriter();
            fileWriter.WriteFpGrowthResults(path, minConfidence, generatedFrequentPatterns);
        }
    }
}